﻿@using System.IO
@using System.Drawing;
@inject Microsoft.AspNetCore.Hosting.IWebHostEnvironment HostEnvironment

@if (ShowFileManager)
{
    <div class="modal" tabindex="-1" style="display:block" role="dialog">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <b class="modal-title">Insert Image</b>
                    <!-- Close Button -->
                    <button type="button" class="close"
                            @onclick="() => { ShowFileManager = false; }">
                        <span aria-hidden="true">X</span>
                    </button>
                </div>
                <div class="modal-body">
                    <div class="row">
                        <RadzenButton Disabled="@(SelectedFile.FileName == null)"
                                      Text="Select"
                                      Click="SelectFile"
                                      ButtonStyle="ButtonStyle.Success"
                                      Style="margin-bottom: 20px;height: 35px" />
                    </div>
                    <div class="row">
                        <div class="col-md-4" style="margin-bottom: 16px">
                            <RadzenTree Change="@LogChange" Data="@Directories"
                                        Expand="@LoadDirectory"
                                        Style="width: 100%; height: 300px">
                                <RadzenTreeLevel Text="@GetTextForNode"
                                                 Template="@FileOrFolderTemplate" />
                            </RadzenTree>
                        </div>
                        <div class="col-md-8" style="margin-bottom: 16px">
                            <RadzenDataList @ref="FileDataList" Data="@Files"
                                            AllowPaging="true" TItem="FileObject"
                                            WrapItems="true" PageSize="6">
                                <Template Context="file">
                                    <RadzenImage Path="@file.FilePath"
                                                 Style="@((file.FileName == SelectedFile.FileName)
                                                          ? $"height:{file.ThumbnailHeight}px;" +
                                                          $"width:{file.ThumbnailWidth}px;" +
                                                          $"padding:10px;background-color:darkgrey;"
                                                          : $"height:{file.ThumbnailHeight}px;" +
                                                          $"width:{file.ThumbnailWidth}px;" +
                                                          $"padding:10px;background-color:white;")"
                                                 Click="@((args) => SelectImage(file))" />
                                </Template>
                            </RadzenDataList>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
}
@code {
    // ImageSelected is an EventCallback that will
    // notify the parent component when an image is selected
    // passing the url of the image to the parent component
    [Parameter] public EventCallback<string> ImageSelected { get; set; }

    private RadzenDataList<FileObject> FileDataList;
    private bool ShowFileManager = false;

    private string CurrentDirectory = "";
    private string CurrentRoot = "";
    private FileObject SelectedFile = new FileObject();
    private List<string> Directories = new List<string>();
    private List<FileObject> Files = new List<FileObject>();
    private Dictionary<DateTime, string> events =
        new Dictionary<DateTime, string>();

    protected override void OnInitialized()
    {
        CurrentRoot =
            Path.Combine(HostEnvironment.WebRootPath, "uploads");
        CurrentDirectory = CurrentRoot;
        Directories.Add(CurrentDirectory);
        LoadFiles();
    }

    public void SetShowFileManager(bool paramSetting)
    {
        ShowFileManager = paramSetting;
    }

    //SelectFile

    private async Task SelectFile()
    {
        await ImageSelected.InvokeAsync(SelectedFile.FilePath);
    }

    // Files

    private void SelectImage(FileObject file)
    {
        if (SelectedFile.FileName == file.FileName)
        {
            SelectedFile = new FileObject();
        }
        else
        {
            SelectedFile = file;
        }
    }

    private void LogChange(TreeEventArgs args)
    {
        // Get the current directory from the
        // argument passed to the method
        CurrentDirectory = args.Value as string;

        // Set the RadzenDataList to page 1
        FileDataList.FirstPage();

        // Reload the FileDataList
        LoadFiles();
    }

    private string GetTextForNode(object data)
    {
        return Path.GetFileName((string)data);
    }

    private RenderFragment<RadzenTreeItem>
        FileOrFolderTemplate = (context) => builder =>
        {
            string path = context.Value as string;
            bool isDirectory = Directory.Exists(path);

            builder.OpenComponent<RadzenIcon>(0);
            builder.AddAttribute(1,
                "Icon", isDirectory ? "folder" :
                "insert_drive_file");

            if (!isDirectory)
            {
                builder.AddAttribute(2,
                    "Style",
                    "margin-left: 24px");
            }
            builder.CloseComponent();
            builder.AddContent(3, context.Text);
        };

    private void LoadDirectory(TreeExpandEventArgs args)
    {
        CurrentDirectory = args.Value as string;

        // Only get the folders not the files
        args.Children.Data =
            Directory.EnumerateFileSystemEntries(CurrentDirectory)
            .Where(x => !x.Contains("."));

        args.Children.Text = GetTextForNode;
        args.Children.HasChildren =
            (path) => Directory.Exists((string)path);
        args.Children.Template = FileOrFolderTemplate;
    }

    private void LoadFiles()
    {
        Files = new List<FileObject>();
        var FileNames =
            Directory.EnumerateFileSystemEntries(CurrentDirectory)
            .Where(x => x.Contains("."));

        foreach (var item in FileNames)
        {
            using (var image = Image.FromFile(item))
            {
                // Calculate Thumbnail
                int thumbnailHeight = 100;
                int thumbnailWidth = 100;
                double x = image.Height / 100;
                if (x > 0)
                {
                    thumbnailHeight = Convert.ToInt32(image.Height / x);
                    thumbnailWidth = Convert.ToInt32(image.Width / x);
                }

                Files.Add(new FileObject()
                {
                    FileName =
                    Path.GetFileName(item),
                    FilePath =
                    item.Replace(HostEnvironment.WebRootPath, "")
                    .Replace("\\uploads", "uploads"),
                    Height = image.Height,
                    Width = image.Width,
                    ThumbnailHeight = Convert.ToInt32(thumbnailHeight),
                    ThumbnailWidth = Convert.ToInt32(thumbnailWidth)
                });
            }
        }

        // Reset selected file
        SelectedFile = new FileObject();

        // Update UI
        StateHasChanged();
    }
}